/**
 * Created by think on 2015/3/5.
 */

var app = require("./app");
var http = require("http").Server(app).listen(9999);
var io = require("socket.io")(http);

var users = {};
io.on("connect", function(socket) {
  var name  = Math.random();
  users[socket.id]={ name: name, socket: socket};

  socket.emit("user_list", get_user_list());
  socket.emit("user_count", get_user_count());
  socket.broadcast.emit("user_count", get_user_count());
  socket.broadcast.emit("server_msg", name+"进入了房间");
  socket.on("edit_nick_name", function(msg, fn) {
    users[socket.id].name = msg;
    io.emit("user_list", get_user_list());
    fn(null, "ok");
  });

  socket.on("msg", function(msg, fn) {
    socket.broadcast.emit("server_new_msg", "一条新消息");
    socket.broadcast.emit("server_msg", msg);
    fn(null, msg);
  });

  socket.on("disconnect", function() {
    var name = "";
    if (users[socket.id]) {
      name = users[socket.id].name;
      delete users[socket.id];
    }
    var keys = Object.keys(users);
    var count = keys.length;
    socket.broadcast.emit("server_msg", name + '离开了房间');
    socket.broadcast.emit("user_count", count);
    socket.broadcast.emit("user_list", get_user_list());
  })
});

function get_user_count() {
  //推送用户列表
  var keys = Object.keys(users);
  var count = keys.length;
  return count;
}

function get_user_list() {
  var keys = Object.keys(users);
  var _tmp_users = [];
  for(var i= 0, ii =keys.length; i<ii; i++) {
    _tmp_users.push({id: keys[i], name: users[keys[i]].name});
  }
  return _tmp_users;
}